#include "sendimg.h"
#include "netheader.h"
#include <QDebug>
#include <QtCore/QBuffer>

extern QUEUE_DATA<MESG> queue_send;

SendImg::SendImg(QObject *parent) : QObject(parent)
{

}

void SendImg::run(){
    WRITE_LOG("start sending picture thread: 0x%p", QThread::currentThreadId());
    qDebug() << "SendImg::run()";
    m_isCanrun = true;
    for(;;){
        queue_lock.lock();
        while(imgqueue.size() == 0){
            bool f = queue_waitCond.wait(&queue_lock, WAITSECONDS * 1000);
            if(f == false){
                QMutexLocker<QMutex> locker(&m_lock);
                if(m_isCanrun == false){
                    queue_lock.unlock();
                    WRITE_LOG("stop sending picture thread: 0x%p", QThread::currentThreadId());
                    return ;
                }
            }
        }

        QByteArray img = imgqueue.front();
        imgqueue.pop_front();
        queue_lock.unlock();
        queue_waitCond.wakeOne();

        MESG *imgsend = (MESG *)malloc(sizeof(MESG));
        if(imgsend == nullptr){
            WRITE_LOG("malloc imgsend failed");
            qDebug() << "malloc imgsend failed";
        }else{
            memset(imgsend, 0, sizeof(MESG));
            imgsend->msg_type = IMG_SEND;
            imgsend->len = img.size();
            qDebug() << "img size :" << img.size();
            imgsend->data = (uchar *)malloc(imgsend->len);
            if(imgsend->data == nullptr){
                free(imgsend);
                WRITE_LOG("malloc imgsend->data failed");
                qDebug() << "malloc imgsend->data failed";
                continue;
            }else{
                memset(imgsend->data, 0 , imgsend->len);
                memcpy_s(imgsend->data, imgsend->len, img.data(), img.size());
                queue_send.push_msg(imgsend);
            }
        }
    }
}

void SendImg::pushToQueue(QImage img){
    QByteArray byte;
    QBuffer buf(&byte);
    buf.open(QIODevice::WriteOnly);
    img.save(&buf, "JPEG");

    QByteArray ss = qCompress(byte);
    QByteArray vv = ss.toBase64();

    queue_lock.lock();
    while(imgqueue.size() > QUEUE_MAXSIZE){
        queue_waitCond.wait(&queue_lock);
    }
    imgqueue.push_back(vv);
    queue_lock.unlock();
    queue_waitCond.wakeOne();
}

void SendImg::ImageCapture(QImage img){
    pushToQueue(img);
}

void SendImg::clearImgQueue(){
    qDebug() << "清空视频队列";
    QMutexLocker locker(&queue_lock);
    imgqueue.clear();
}

void SendImg::stopImmediately(){
    QMutexLocker locker(&m_lock);
    m_isCanrun = false;
}
